package com.longdaji.decoration.ui.main.home;

import android.content.Intent;
import android.graphics.Color;
import android.os.Parcelable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.longdaji.decoration.R;
import com.longdaji.decoration.base.BaseFragment;
import com.longdaji.decoration.bean.Account;
import com.longdaji.decoration.data.bean.Advertisment;
import com.longdaji.decoration.data.bean.GoodsCategory;
import com.longdaji.decoration.data.bean.GoodsChosensBean;
import com.longdaji.decoration.data.bean.GoodsMotifsBean;
import com.longdaji.decoration.ui.assistant.AssistantActivity;
import com.longdaji.decoration.ui.goodscategory.GoodsCategoryActivity;
import com.longdaji.decoration.ui.news.InfoActivity;
import com.longdaji.decoration.ui.signin.SignInActivity;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by longtao on 2018/1/14.
 */

public class HomeFragment extends BaseFragment implements HomeContract.View {
    private String TAG = HomeFragment.class.getSimpleName();
    @BindView(R.id.recycler_view_brand)
    RecyclerView mRecyclerViewBrand;
    @BindView(R.id.roll_pager_view)
    RollPagerView mRollPagerView;
    @BindView(R.id.top_roll_pager)
    RollPagerView mTopRollPager;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.iv_classify)
    ImageView mIvClassify;
//    @BindView(R.id.iv_home_back)
//    ImageView mIvHomeBg;
    @Inject
    HomeContract.Presenter mPresenter;
    private List<GoodsCategory.SecondCategory> mBrandList = new ArrayList<>();
    private List<Advertisment> mAdList = new ArrayList<>();
    private HomeBrandAdapter adapter;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption;
    private List<GoodsCategory.SecondCategory> mCategoryList;
    private LooperAdapter mLoopAdapter;
    private List<GoodsMotifsBean.GoodsMotifs> mGoodsMotifs;
    private ShareAction mShareAction;
    private String mShareUrl;
    private TopLooperAdapter mTopLoopAdapter;

    @Inject
    public HomeFragment() {
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        if (mPresenter != null)
            mPresenter.setView(this);
        //initBrandList();
        //初始化定位
        initLocation();
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3, OrientationHelper.VERTICAL, false);
        mRecyclerViewBrand.setLayoutManager(layoutManager);
        adapter = new HomeBrandAdapter(getActivity(), mBrandList);
        //mRecyclerViewBrand.addItemDecoration(new GridSpacingItemDecoration(2, 10, false));
        mRecyclerViewBrand.setAdapter(adapter);
        Log.d(TAG, "homefragment is onCreateView");

        // initAdList();
        //设置播放时间间隔
        mRollPagerView.setPlayDelay(3000);
        //设置透明度
        mRollPagerView.setAnimationDurtion(500);
        //设置适配器
        mLoopAdapter = new LooperAdapter(getActivity(), mRollPagerView, new ArrayList<GoodsChosensBean.GoodsChosensImg>());
        mRollPagerView.setAdapter(mLoopAdapter);
        mRollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.BLACK, R.color.line_color));
        // initAdList();
        //设置播放时间间隔
        mTopRollPager.setPlayDelay(3000);
        //设置透明度
        mTopRollPager.setAnimationDurtion(500);
        //设置适配器
        mTopLoopAdapter = new TopLooperAdapter(getActivity(), mTopRollPager, new ArrayList<GoodsMotifsBean.GoodsMotifs>());
        mTopRollPager.setAdapter(mTopLoopAdapter);
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible) {
            getGoodsCatergory();
            getTopicImage();
            getChosenImages();
            mPresenter.getShareUrl();
        }
    }

    private void getChosenImages() {
        mPresenter.getChosenImages();
    }

    private void getTopicImage() {
        mPresenter.getTopicImage();
    }

    @Override
    public void onDestroy() {
        if (mPresenter != null)
            mPresenter.detachView();
        destroyLocation();
        super.onDestroy();
    }


    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(getActivity().getApplicationContext());
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        locationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
//设置定位参数
        locationClient.setLocationOption(locationOption);
        locationClient.startLocation();
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation loc) {
            if (null != loc) {
                //解析定位结果
                mTvLocation.setText(loc.getCity() + "...");
            } else {
                mTvLocation.setText("定位失败");
            }
        }
    };

    private void getGoodsCatergory() {
        mPresenter.getGoodsCatergory();
    }

//    private void initAdList() {
//        for (int i = 0; i < 6; i++) {
//            Advertisment ad = new Advertisment(R.mipmap.banner_back, "我带着这幅耳环去聚会，朋友都问我要链接！", "走在人群中，你是想变身万众焦点还是甘愿沦为背景板？靠一两点来点缀自己！");
//            mAdList.add(ad);
//        }
//    }

//    private void initBrandList() {
//        for (int i = 0; i < 6; i++) {
//            Brand brand = new Brand("手链", R.mipmap.icon_brand_bracelet);
//            mBrandList.add(brand);
//        }
//
//    }

    @OnClick({R.id.tv_location, R.id.iv_news, R.id.tv_apply_assistant, R.id.tv_sign_in, R.id.iv_classify, R.id.tv_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            case R.id.tv_location:
//                startActivity(LocationActivity.getStartIntent(getActivity()));
//                break;
            case R.id.iv_news:
                startActivity(InfoActivity.getStartIntent(getActivity()));
                break;
            case R.id.tv_apply_assistant:
                if (Account.getInstance().getUserid() == null) {
                    toast("请先登录账户");
                    return;
                }
                startActivity(AssistantActivity.getStartIntent(getActivity()));
                break;
            case R.id.tv_sign_in:
                if (Account.getInstance().getUserid() == null) {
                    toast("请先登录账户");
                    return;
                }
                startActivity(SignInActivity.getStartIntent(getActivity()));
                break;
            case R.id.iv_classify:
                Intent intent = GoodsCategoryActivity.getStartIntent(getActivity());
                intent.putParcelableArrayListExtra("category_list", (ArrayList<? extends Parcelable>) mCategoryList);
                startActivity(intent);
                break;
//            case R.id.iv_home_back:
//                Intent intent1 = BannerImageActivity.getStartIntent(getActivity());
//                intent1.putExtra("title", "精选图片");
//                intent1.putExtra("image", mGoodsMotifs.getBannerImgAddress());
//                getActivity().startActivity(intent1);
//                break;
            case R.id.tv_share:
                if (mShareUrl == null) {
                    return;
                }
                mShareAction.open();
                break;

            default:
                break;
        }
    }

    @Override
    public void showCategoryList(List<GoodsCategory.SecondCategory> list) {
        Log.d(TAG, "showCategoryList is " + list);
        adapter.setData(list);
        mCategoryList = list;
    }

    @Override
    public void showTopicImage(List<GoodsMotifsBean.GoodsMotifs> goodsMotifs) {
        mGoodsMotifs = goodsMotifs;
//        if (goodsMotifs != null) {
//            GlideUtils.loadImage(this, goodsMotifs.getImgAddress(), mIvHomeBg, null, R.drawable.no_banner, R.drawable.no_banner);
//        } else {
//            GlideUtils.loadImage(this, null, mIvHomeBg, null, R.drawable.no_banner, R.drawable.no_banner);
//        }
        mTopLoopAdapter.setData(goodsMotifs);
    }

    @Override
    public void showChosenImages(List<GoodsChosensBean.GoodsChosensImg> imageList) {
        Log.d(TAG, "showChosenImages is " + imageList);
        mLoopAdapter.setData(imageList);
    }

    @Override
    public void showShareUrl(final String url) {
        if(url==null){
            return;
        }
        mShareUrl = url;
             /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(getActivity()).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        UMWeb web = new UMWeb(url);
                        web.setTitle("桃心");
                        web.setThumb(new UMImage(getActivity(), R.mipmap.launcher_icon));
                        web.setDescription("一个专卖女生饰品的APP");
                        new ShareAction(getActivity()).withMedia(web)
                                .setPlatform(share_media)
                                .setCallback(shareListener).share();
                    }

                });
    }

    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(getActivity(), "成功了", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getActivity(), "失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(getActivity(), "取消了", Toast.LENGTH_LONG).show();

        }
    };
}
